<?php

namespace app\common\model\banxi\organization;

use app\common\enums\ClassHourTypeEnum;
use app\common\enums\LevelTypeEnum;
use app\common\model\common\BaseModel;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 机构等级配置
 */
class OrganizationLevelConfig extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_organization_level_config';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'levelTypeCn',
        'isUplevel'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'rechargeOnlineStudent' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------


    public function getLevelTypeCnAttr($value, $data): string
    {
        $value = $value ?: ($data['levelType'] ?? '');
        return (new LevelTypeEnum())->getDescription($value) ?? '';
    }

    public function getIsUplevelAttr($value, $data)
    {
        $value = $value ?: ($data['id'] ?? '');
        $levelType = $data['levelType'];

        // 定义可升级的等级ID映射
        $upgradeableLevels = [
            LevelTypeEnum::E1 => [1, 2],
            LevelTypeEnum::E2 => [4, 5]
        ];

        // 如果当前等级类型存在于可升级映射中，且当前ID在可升级列表内，则允许升级
        if (isset($upgradeableLevels[$levelType]) && in_array($value, $upgradeableLevels[$levelType])) {
            return true;
        }

        // 其他情况默认为不可升级
        return false;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->withCount([
            'organizationNum' => 'organizationNum'
        ])->where($where)->order(['sortNum' => 'desc', 'id' => 'desc'])->paginate([
            'page' => $page,
            'list_rows' => $limit
        ]);
    }

    public function getListSelectPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->where($where)->order(['sortNum' => 'desc', 'id' => 'desc'])->paginate([
            'page' => $page,
            'list_rows' => $limit
        ]);
    }

    public function getInfo(array $where)
    {
        return $this->withCount([
            'organizationNum' => 'organizationNum'
        ])->where($where)->find();
    }

    public function saveOrUpdate(array $data)
    {
        $id = $data['id'] ?? 0;
        if (!$id) {
            $this->save($data);
        } else {
            $info = $this->where(['id' => $id])->find();
            if (empty($info)) {
                throw new ValidateException('机构等级不存在');
            }
            $info->save($data);
        }
        return true;
    }

    public function del(int $levelId)
    {

        $levelInfo = $this->where(['id' => $levelId])->find();
        if (!$levelInfo) {
            throw new ValidateException('记录不存在');
        }
        $count = Organization::where(['level' => $levelId])->count();
        if ($count > 0) {
            throw new ValidateException('该等级下有机构，不能机构');
        }
        $levelInfo->delete();
        return true;

    }

    public function classHourAmount($levelConfig, $classHourType)
    {
        switch ($classHourType) {
            case ClassHourTypeEnum::C_30:
                return $levelConfig['price30'];
            case ClassHourTypeEnum::C_60:
                return $levelConfig['price60'];
            default:
                return 0;
        }
    }

    //判断身份
    public function judgeLevelIdentity($id, $levelType)
    {
        $info = $this->where(['id' => $id])->field('levelType')->find();
        if (empty($info)) {
            //机构等级不存在
            return false;
        }
        if ($info['levelType'] != $levelType) {
            return false;
        }
        return true;

    }

    public function getLevelConfig($level, $rewordField)
    {
        return $this->where(['id' => $level])->value($rewordField);
    }

    public function getNextLevel($id, $levelType)
    {
        return $this->where([
            ['id', '<', $id],
            ['levelType', '=', $levelType]
        ])->order('id', 'desc')->find();
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function organizationNum()
    {
        return $this->hasMany(Organization::class, 'level', 'id');
    }

}